package com.sy.cloud.guess.controller;

import com.alibaba.fastjson.JSONObject;
import com.gok.pay.wx.SignType;
import com.gok.pay.wx.WXPayConfig;
import com.gok.pay.wx.WXPayRequest;
import com.gok.pay.wx.WXPayUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sy.cloud.guess.model.TiOrder;
import com.sy.cloud.guess.service.IWxConfigService;
import com.sy.common.model.Juejinuser;
import com.sy.common.persistence.BaseService;
import com.sy.common.service.IBaseService;
import com.sy.common.service.ITestService;
import com.sy.common.service.TestService;
import com.sy.common.util.Funutil;
import com.sy.shiro.UsernameToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.DoubleBinaryOperator;
import java.util.function.Function;

/**
 * Created by mac on 2018/1/2.
 */
@Controller
@Slf4j
@RequestMapping("/cashout")
public class CashoutController {
    @Resource
    private IWxConfigService wxConfigService;

    @Resource
    private ITestService testService;

    @Resource
    private IBaseService baseService;
    /**
     * 98提现
     * price
     * plat
     * cardnum
     * idNumber
     * name
     * @return
     */
    @RequestMapping(value = "/cashoutaction", method = RequestMethod.POST)
    public JSONObject cashoutAction(HttpServletRequest request, HttpServletResponse response, TiOrder tiOrder) throws Exception {
        JSONObject resultObject = new JSONObject();
        if( testService.updateTiOrder( tiOrder ) ){// 刷新了1张表，就是把tiOrder新增到数据库里
//        if( true ){// 刷新了2张表
            Date date=new Date();
            DateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
            String req_time = format.format(date);
            // 开始调用98的提现接口
            String head_code = Funutil.cardIfActive( tiOrder.getCardnum(), req_time );
            log.info("head——code的值"+head_code);

            String url = "http://scpay.shopping98.com/v1/gateway.shtml";
            MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
            String nonce = WXPayUtil.generateUUID();

            Map<String, String> maps= new HashMap<String, String>();
            maps.put("service","v1_liquidation_pay");
            maps.put("version","1.0");
            maps.put("merchant_no","676988092351791104");
            maps.put("charset","UTF-8");
            maps.put("req_time",req_time);
            maps.put("sign","");
            maps.put("sign_type","MD5");
            maps.put("nonce_str",nonce);
            maps.put("out_trade_no", tiOrder.getOrdersn());
            int amount = (int)(tiOrder.getPrice()*100);
            maps.put("amount", amount+"");// 分为单位
            maps.put("account_no", tiOrder.getCardnum());
            maps.put("account_name", tiOrder.getWeixin());
            maps.put("account_type", "00");
            maps.put("client_ip", "127.0.0.1");
            maps.put("order_time", req_time);
            maps.put("id_type", "0");
            maps.put("id", tiOrder.getIdnumber());
            if( head_code == null || head_code.equals("") ){
            }else{
                maps.put("bank_code", head_code);
            }
            maps.put("currency", "CNY");
            maps.put("notify_url", "http://gok.tc2stgs.com/cashout/cashoutnotify");
            maps.put("attach", tiOrder.getPtmoney()+"" );

            String sign = WXPayUtil.generateSignature2(maps, "3eced11b140c44a4be53561adf92acf8", SignType.MD5);
            maps.put("sign", sign);
            for (Map.Entry<String, String> entry : maps.entrySet()) {
                params.add(entry.getKey(), entry.getValue());
            }
            // 最关键的地方
            String result = null;
            result = Funutil.restRequest(url,params);
            log.info("同步接口返回");
            log.info(result);
            Gson gson = new Gson();
            Map<String, String> mapsresult = gson.fromJson(result, new TypeToken<Map<String, String>>() {}.getType());


            if( result != null ){
                if( mapsresult.get("resp_code").equals("0000") ){
                    if( mapsresult.get("trans_status").equals("S") ){
                        testService.cashsuccess(Double.parseDouble( mapsresult.get("attach") ), mapsresult.get("ordersn"));
                        response.getWriter().print("success");
                        resultObject.put("status","1");
                    }else if( mapsresult.get("trans_status").equals("F") ){
                        testService.cashfail(mapsresult.get("ordersn"), "S");
                        resultObject.put("status","0");
                        response.getWriter().print("success");
                    }
                }
            }

            resultObject.put("message",mapsresult.get("resp_msg"));
        }
        return resultObject;
    }


    /**
     * 98提现通知接口
     * @return    cashout/cashoutnotify
     */
    @RequestMapping(value = "/cashoutnotify", method = RequestMethod.GET)
    public void cashoutNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        StringBuilder wholeStr = new StringBuilder();
        try {
            BufferedReader br = request.getReader();
            String str;
            while((str = br.readLine()) != null){
                wholeStr.append(str);
            }
        } catch (IOException e) {
            log.error("getBodyString error", e);
        }
        log.info( "提现异步接口返回" );
        log.info( wholeStr.toString() );
        log.info( "" );
        Map<String, String> map= new HashMap<String, String>();

        String ss = wholeStr.toString();
        String[] sArray1 = ss.split("&");
        for( int i =0;i< sArray1.length; i++  ){
            String[] sArray2 = sArray1[i].split("=");
            map.put( sArray2[0], sArray2[1] );
        }

        String sign = WXPayUtil.generateSignature2(map, "3eced11b140c44a4be53561adf92acf8", SignType.MD5);
        if( sign.equals(map.get("sign")) ){
            //签名验证通过
            if( map.get("resp_code").equals("0000") && map.get("trans_status").equals("S") ){
                testService.cashsuccess(Double.parseDouble( map.get("attach") ), map.get("out_trade_no"));
            }
        }

    }

    /**
     * 提现轮询接口
     */
    @RequestMapping(value = "/cashQueryOrder", method = RequestMethod.GET)
    public void cashQueryOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url= "http://scpay.shopping98.com/v1/gateway.shtml";
        List< TiOrder > tiOrders = testService.getTiList("98" );
        for( int i =0; i< tiOrders.size(); i++ ){
            Map<String,String> para1 = new HashMap<>();
            MultiValueMap<String, String> para2= new LinkedMultiValueMap<String, String>();
            para1.put("out_trade_no", tiOrders.get(i).getOrdersn());
            para1.put("service", "v1_liquidation_query");
            para1.put("version", "1.0");
            para1.put("merchant_no", "676988092351791104");
            para1.put("charset", "UTF-8");
            Date day=new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
            para1.put("req_time", df.format(day));
//            para1.put("sign", df.format(day));
            para1.put("sign_type", "MD5");
            para1.put("nonce_str", WXPayUtil.generateUUID());


            String sign = WXPayUtil.generateSignature2(para1, "3eced11b140c44a4be53561adf92acf8", SignType.MD5);
            para1.put("sign", sign);


            for (Map.Entry<String, String> entry : para1.entrySet()) {
                para2.add(entry.getKey(), entry.getValue());
            }

            String result = Funutil.restRequest(url,para2);
            Gson gson = new Gson();
            if( result == null ){
                continue;
            }

            Map<String, String> mapsresult = gson.fromJson(result, new TypeToken<Map<String, String>>() {}.getType());

            log.info( gson.toJson( mapsresult ) );
            if( mapsresult.get("resp_code").equals("0000") ){
                if( mapsresult.get("trans_status").equals("S") ){
                    testService.cashsuccess( Double.parseDouble(mapsresult.get("attach")), mapsresult.get("out_trade_no") );
                }
            }else{
                testService.cashfail( tiOrders.get(i).getOrdersn(), mapsresult.get("resp_msg") );
            }
        }

    }
}
